package cn.wolfcode.web.interceptor;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.util.RequiredPermission;
import cn.wolfcode.util.UserContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class CheckPermissionInterceptor implements HandlerInterceptor {


    @Autowired
    private IPermissionService permissionService;

    // 检查权限
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        System.out.println(request.getRequestURI());

        // 获取访问员工对象
        Employee employee = UserContext.getEmployee();
        if (employee.isAdmin()) { // 是管理员
            return true;
        }
        // 不是管理员
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        RequiredPermission annotation = handlerMethod.getMethodAnnotation(RequiredPermission.class);
        if (annotation == null) {
            return true;
        }
        // 获取当前访问方法权限表达式
        String expression = annotation.expression();
        // 查询当前访问员工权限
        List<String> expressions = UserContext.getExpressions();
        if (expressions.contains(expression)) { // 访问的员工有此权限
            return true;
        }
        // 不是管理员, 方法需要权限控制, 但此员工又没有权限
        response.sendRedirect("/nopermission");
        return false;
    }
}
